<?php

namespace App\Http\Middleware;

use App\Models\Permission;
use Closure;
use Illuminate\Http\Request;


/**
 * 检查管理员是否有权限 访问该模块
 */
class CheckAdminPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        //  $request->manage_id = 1;
        //  return $next($request);

        $auth = $this->checkAdminAuth($request);

        if (!$auth) {
            return  response()->json(['code' => 206, 'msg' => '暂无权限使用该模块']);
        }
        return $next($request);
    }


    /**
     * 检查用户权限
     *
     */
    public function checkAdminAuth($request)
    {
        if ($request->manage_id == 1) {
            return true;
        }

        $request_url = $request->path();
        $permissionModelobj = new Permission();

        /*过滤列表*/
        $sameApiList = [
            // 'api/newsTypeSimple/list',
        ];
        if (in_array($request_url, $sameApiList)) {
            return true;
        }

        $permission_id = $permissionModelobj->getUserPermissionId($request->manage_id);

        $permission_list = $permissionModelobj
            ->select('id', 'api_path')
            ->where('api_path', 'like', "%$request_url%")
            ->where('is_del', 1)
            ->whereIn('id', $permission_id)
            ->get();

        /*检查该路径是否存在*/
        if ($permission_list->isEmpty()) {
            return  false;
        }

        foreach ($permission_list as $key => $val) {
            $api_path = explode(',', $val['api_path']);
            if (in_array($request_url, $api_path)) {
                return true;
            }
        }
        return  false;
    }
}
